import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import classnames from 'classnames';
import {View, Text} from '@tarojs/components';
import calendarObj from '../../../utils/calendar';
import './components.scss';

export default class CalendarScenic extends Component {

  constructor(props) {
    super(props);
  }

  state = {
    weeks: ["日", "一", "二", "三", "四", "五", "六"],
    todayDate: calendarObj.getCurrentDate(),
    realCurYear: calendarObj.getCurrentDate().split("-")[0],
    realCurMonth: calendarObj.getCurrentDate().split("-")[1],
    curYear: calendarObj.year,
    curMonth: calendarObj.month,
    month: [],
  }

  chooseDate
  initLoad = true

  componentDidUpdate() {
    this.chooseDate = this.props.currentDate
    if (this.props.visible && this.state.month.length === 0) {
      this.initLoad = true
      this.getCalendar(this.props.calendarData);
    }
  }

  // 返回
  handleBack() {
    const tempDate = this.state.todayDate;
    calendarObj.loadCurrentMonthDate(tempDate);
    this.setState({
      curYear: calendarObj.year,
      curMonth: calendarObj.month
    }, () => {
      this.getCalendar(this.props.calendarData);
    })
  }
  // 切换月份
  handleChangeMonth(flag) {
    const {month, curMonth} = this.state;

    Taro.hideToast();
    const m = parseInt(curMonth);
    const d = this.chooseDate && this.chooseDate.date ? this.chooseDate.date.split("-")[2] : calendarObj.curMonthEveryDay[0];

    if(flag === "last") calendarObj.showLastMonth(m, d);
    else calendarObj.showNextMonth(m, d);

    this.setState({
      curYear: calendarObj.year,
      curMonth: calendarObj.month
    }, () => {
      this.getCalendar(this.props.calendarData);
    });
  }

  // 获取日历
  getCalendar(datas) {
    const {weeks} = this.state;
    this.setState(state => ({
      month: state.month.splice(0)
    }))
    Taro.showLoading({
      title: "加载中"
    })
    let newData = calendarObj.allDates.map(item => ({
      ...item,
      valid: false,
      group_id: null,
      price: 0,
      stock_balance: 0,
      surplus_stock: 0,
      label: "周" + weeks[new Date(item.date).getDay()],
    }));
    let nextStartIdx = 0; // 内循环的开始索引
    for(let i = 0, len = newData.length; i < len; i++) {
      for(let j = nextStartIdx, len2 = datas.length; j < len2; j++) {
        if(newData[i].date === datas[j].date) {
          nextStartIdx = j;
          newData[i] = Object.assign(
            {
              ...newData[i],
              ...datas[j],
              valid: datas[j].price > 0 && datas[j].surplus_stock > 0 && datas[j].stock_balance > 0
            }
          );
          break;
        }
      }
    }
    // console.log("newData : ", newData)
    this.initLoad = false
    this.setState({month: newData}, () => {
      Taro.hideLoading();
    });
  }

  // 点击日期
  clickDate(item) {
    if (!item.valid || this.chooseDate.date === item.date) return;

    if (item.stock_balance === 0) {
      Taro.showToast({
        title: "已售罄",
        icon: "none"
      })
      return;
    }

    this.chooseDate = item
    this.props.handleSureDate({date: this.chooseDate});
  }

  // 取消
  closeCalendar() {
    this.props.closeCalendar();
  }

  // 确定
  sureChoose() {
    this.props.handleSureDate({date: this.chooseDate});
  }

  render() {
    const {goods} = this.props;
    const {
      realCurYear,
      realCurMonth,
      curYear,
      curMonth,
      weeks,
      month,
    } = this.state;

    return (
      <View className={classnames("calendar-page", {
        'cal-show': this.props.visible
      })}
      >
        <View className='mth-bar'>
          <View className='wth left'>
            <Text className='mth-btn' onClick={() => this.handleChangeMonth('last')}>上一月</Text>
          </View>
          <View className='mid'>
            {
              (realCurMonth != curMonth || realCurYear != curYear) && 
              <Text class="today" onClick={() => this.handleBack()}>今天</Text>
            }
            <Text>{curYear}年{curMonth}月</Text>
          </View>
          <View className='wth right'>
            <Text className='mth-btn' onClick={() => this.handleChangeMonth('next')}>下一月</Text>
          </View>
        </View>

        <View className='week-bar'>
          {
            weeks.map((item, index) => (
              <View key={index}>{item}</View>
            ))
          }
        </View>
        {
          month.length > 0 &&
          <View className='calendar-container'>
            {
              month.map((item, index) => (
                <View
                  key={index}
                  onClick={() => this.clickDate(item)}
                  className={classnames("calendar-block", {
                    ['active']: this.chooseDate && this.chooseDate.fullName == item.date
                  })}
                >
                  <View className='block-item'>
                    <View className='date'>
                      {/*!item.isCurMonth && <Text className='month'>{item.month}月</Text>*/}
                      <Text className={classnames({
                        ['normal-date']: item.isCurrentMonth,
                        ['disabled-date']: !item.valid,
                        ['disabled-normal-date']: item.isCurrentMonth && !item.valid
                      })}
                      >{item.day}日</Text>
                    </View>
                    {
                      item.valid &&
                      <View className={classnames('date-info', {['date-info-disabled']: !item.isCurrentMonth})}>
                        <View>价:￥{item.price}</View>
                        <View>余: {item.surplus_stock}</View>
                        {
                          item.stock_balance && item.stock_balance > 0 && item.stock_balance <= 10 &&
                          <View className='red'>
                            <Text>票务紧张</Text>
                          </View>
                        }
                        {
                          !item.stock_balance &&
                          <View className='red'>
                            {
                              goods.category == 1 && <Text>售罄</Text>
                            }
                          </View>
                        }
                      </View>
                    }
                  </View>
                </View>
              ))
            }
          </View>
        }
        {
          month.length === 0 && this.initLoad && <View className='empty-calendar'>加载中...</View>
        }
        {
          month.length === 0 && !this.initLoad && <View className='empty-calendar'>暂无可约日期</View>
        }
      </View>
    )
  }
}
